﻿using CQIE.LabAssist.DataAccesss;
using CQIE.LabAssist.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

namespace CQIE.LabAssist.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CheckController : ControllerBase
    {
        private readonly ICheckService _checkService;

        public CheckController(ICheckService CheckService)
        {
            _checkService = CheckService;
        }

        #region 新增检查记录
        public record check
        {
            public bool Doors_windows { get; set; }
            /// <summary>
            /// 门窗状态备注，描述门窗的具体情况
            /// </summary>
            public string Doors_windows_state { get; set; }
            /// <summary>
            /// 电器线路状态，表示电器线路是否正常
            /// </summary>
            public bool Electrical_wiring { get; set; }
            /// <summary>
            /// 电器线路备注，描述电器线路的具体情况
            /// </summary>
            public string Electrical_wiring_state { get; set; }
            /// <summary>
            /// 消防器件有无，表示消防器件是否存在
            /// </summary>
            public bool Firefighting_facilities { get; set; }
            /// <summary>
            /// 消防器件有无备注，描述消防器件的具体情况
            /// </summary>
            public string Firefighting_facilities_state { get; set; }

            /// <summary>
            /// 消防器件有效期，表示消防器件是否在有效期内
            /// </summary>
            public bool Firefighting_facilities_validity { get; set; }

            /// <summary>
            /// 消防器件有效期备注，描述消防器件有效期的具体情况
            /// </summary>
            public string Firefighting_facilities_validity_state { get; set; }

            /// <summary>
            /// 仪器设备能否使用，表示仪器设备是否可正常使用
            /// </summary>
            public bool Instruments_equipment { get; set; }

            /// <summary>
            /// 仪器设备能否使用备注，描述仪器设备的具体情况
            /// </summary>
            public string Instruments_equipment_state { get; set; }

            /// <summary>
            /// 防盗设施是否完好，表示防盗设施是否完好无损
            /// </summary>
            public bool Anti_theft_facilities { get; set; }

            /// <summary>
            /// 防盗设施是否完好备注，描述防盗设施的具体情况
            /// </summary>
            public string Anti_theft_facilities_state { get; set; }

            /// <summary>
            /// 警示标志，表示是否有警示标志
            /// </summary>
            public bool Warning_sign { get; set; }

            /// <summary>
            /// 警示标志备注，描述警示标志的具体情况
            /// </summary>
            public string Warning_sign_state { get; set; }

            /// <summary>
            /// 设备仪器其他安全隐患，表示设备仪器是否存在其他安全隐患
            /// </summary>
            public bool IEOther_safety_hazards { get; set; }

            /// <summary>
            /// 设备仪器其他安全隐患备注，描述设备仪器的其他安全隐患
            /// </summary>
            public string IEOther_safety_hazards_state { get; set; }

            /// <summary>
            /// 物品及清洁，表示物品的摆放和清洁情况是否良好
            /// </summary>
            public bool Item_hygiene { get; set; }

            /// <summary>
            /// 物品及清洁备注，描述物品摆放和清洁的具体情况
            /// </summary>
            public string Item_hygiene_state { get; set; }

            /// <summary>
            /// 其他安全隐患，表示是否存在其他安全隐患
            /// </summary>
            public bool Other_safety_hazards { get; set; }

            /// <summary>
            /// 其他安全隐患备注，描述其他安全隐患的具体情况
            /// </summary>
            public string Other_safety_hazards_state { get; set; }

            /// <summary>
            /// 所属学期ID
            /// </summary>
            public int semesterId { get; set; }

            /// <summary>
            /// 实验室ID
            /// </summary>
            public List<int> laboratoryIds { get; set; }
        }

        // 建立队列工厂
        RabbitMQ.Client.IConnectionFactory factory = new ConnectionFactory
        {
            HostName = "127.0.0.1", // IP地址
            Port = 5672, // 端口号
            UserName = "guest", // 用户账号
            Password = "guest" // 用户密码
        };
        /// <summary>
        /// 新增检查记录
        /// </summary>
        /// <param name="check"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult addCheck()
        {
            //需要连接的消息服务代理(Broker)配置
            var factory = new RabbitMQ.Client.ConnectionFactory();
            factory.HostName = "127.0.0.1";
            factory.UserName = "guest";
            factory.Password = "guest";
            factory.Port = 5672;//默认端口5672

            //第一步：连接RabbitMQ
            using (var connection = factory.CreateConnection())
            {
                Console.WriteLine($"收到消息：1");
                //第二部：创建信道
                using (var channel = connection.CreateModel())
                {
                    Console.WriteLine($"收到消息：2");

                    //定义队列
                    string queueName = "laboratory-queue";
                    var queue = channel.QueueDeclare(queueName, false, false, false, null);

                    //同一时刻服务器只发送一条消息给消费者
                    channel.BasicQos(0, 1, false);

                    //定义消费者
                    var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel);

                    //消费者接收到消息后的处理
                    consumer.Received += (sender, e) =>
                    {
                        Console.WriteLine($"收到消息：3");

                        try
                        {
                            //将消息转为期望的格式
                            var jsonStr = System.Text.Encoding.UTF8.GetString(e.Body.ToArray());
                            Console.WriteLine($"收到消息：{jsonStr}");
                            var check = Newtonsoft.Json.JsonConvert.DeserializeObject<check>(jsonStr);

                            if (check != null)
                            {
                                Console.WriteLine("开始处理消息");
                                bool processed = false;
                                if (true)
                                {
                                    List<int> checkRecodHelps = new List<int>();

                                    Check newcheck = new Check
                                    {
                                        Anti_theft_facilities = check.Anti_theft_facilities,
                                        Anti_theft_facilities_state = check.Anti_theft_facilities_state,
                                        Doors_windows = check.Doors_windows,
                                        Doors_windows_state = check.Doors_windows_state,
                                        Electrical_wiring = check.Electrical_wiring,
                                        Electrical_wiring_state = check.Electrical_wiring_state,
                                        Firefighting_facilities = check.Firefighting_facilities,
                                        Firefighting_facilities_state = check.Firefighting_facilities_state,
                                        Firefighting_facilities_validity = check.Firefighting_facilities_validity,
                                        Firefighting_facilities_validity_state = check.Firefighting_facilities_validity_state,
                                        Instruments_equipment = check.Instruments_equipment,
                                        Instruments_equipment_state = check.Instruments_equipment_state,
                                        Warning_sign = check.Warning_sign,
                                        Warning_sign_state = check.Warning_sign_state,
                                        IEOther_safety_hazards = check.IEOther_safety_hazards,
                                        IEOther_safety_hazards_state = check.IEOther_safety_hazards_state,
                                        Item_hygiene = check.Item_hygiene,
                                        Item_hygiene_state = check.Item_hygiene_state,
                                        Other_safety_hazards = check.Other_safety_hazards,
                                        Other_safety_hazards_state = check.Other_safety_hazards_state,
                                        semesterId = check.semesterId
                                    };
                                    for (int i = 0; i < check.laboratoryIds.Count; i++)
                                    {
                                        newcheck.laboratoryId = check.laboratoryIds[i];

                                        try
                                        {
                                            //checkRecodHelp.Success = _checkService.addCheck(newcheck);
                                            _checkService.addCheck(newcheck);
                                        }
                                        catch (Exception ex)
                                        {
                                            //checkRecodHelp.Success = false;
                                            //checkRecodHelp.reason = ex.ToString();

                                            checkRecodHelps.Add(check.laboratoryIds[i]);
                                        }

                                    }
                                    processed = true;
                                }
                                if (processed)
                                {
                                    //消息成功处理后，向消息队列返回确认状态
                                    channel.BasicAck(e.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            //消息成功处理后，向消息队列返回确认状态
                            channel.BasicAck(e.DeliveryTag, false);
                            Console.WriteLine("消费者错误" + ex.Message);
                        }
                    };
                    string consumerTag = "book-counsumer";
                    channel.BasicConsume(queueName, false, consumerTag, false, false, null, consumer);

                    Console.WriteLine("按回车结束");
                    Console.ReadLine();
                }
                return Ok();
            }

        }
        #endregion
        [HttpPost]
        public IActionResult addChecktwo()
        {
            string JWTResult = "";

            //创建连接工厂对象
            IConnectionFactory factory = new ConnectionFactory
            {
                HostName = "127.0.0.1", //IP地址
                Port = 5672, //端口号
                UserName = "guest", //用户账号
                Password = "guest" //用户密码
            };

            //创建连接和通道
            var connection = factory.CreateConnection();
            var channel = connection.CreateModel();

            try
            {
                #region 项目B监听接收登录的队列消息
                // 使用已定义的队列名称
                string queueName = "login-queue";

                //同一时刻，服务器只发一条消息给消费者
                channel.BasicQos(0, 1, false);

                // 设置消费者监听队列
                var consumer = new EventingBasicConsumer(channel);
                //配置消费者对象
                consumer.Received += (model, ea) =>
                {
                    bool processed = true;

                    try
                    {
                        var body = ea.Body.ToArray();
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received '{0}':'{1}'", ea.RoutingKey, message);
                        // 反序列化JSON字符串为匿名对象
                        var messageObject = JsonConvert.DeserializeObject<dynamic>(message);

                        //将消息转为期望的格式
                        var jsonStr = System.Text.Encoding.UTF8.GetString(ea.Body.ToArray());
                        Console.WriteLine($"收到消息：{jsonStr}");
                        var check = Newtonsoft.Json.JsonConvert.DeserializeObject<check>(jsonStr);

                        if (check != null)
                        {
                            Console.WriteLine("开始处理消息");
                             processed = false;
                            if (true)
                            {
                                List<int> checkRecodHelps = new List<int>();

                                Check newcheck = new Check
                                {
                                    Anti_theft_facilities = check.Anti_theft_facilities,
                                    Anti_theft_facilities_state = check.Anti_theft_facilities_state,
                                    Doors_windows = check.Doors_windows,
                                    Doors_windows_state = check.Doors_windows_state,
                                    Electrical_wiring = check.Electrical_wiring,
                                    Electrical_wiring_state = check.Electrical_wiring_state,
                                    Firefighting_facilities = check.Firefighting_facilities,
                                    Firefighting_facilities_state = check.Firefighting_facilities_state,
                                    Firefighting_facilities_validity = check.Firefighting_facilities_validity,
                                    Firefighting_facilities_validity_state = check.Firefighting_facilities_validity_state,
                                    Instruments_equipment = check.Instruments_equipment,
                                    Instruments_equipment_state = check.Instruments_equipment_state,
                                    Warning_sign = check.Warning_sign,
                                    Warning_sign_state = check.Warning_sign_state,
                                    IEOther_safety_hazards = check.IEOther_safety_hazards,
                                    IEOther_safety_hazards_state = check.IEOther_safety_hazards_state,
                                    Item_hygiene = check.Item_hygiene,
                                    Item_hygiene_state = check.Item_hygiene_state,
                                    Other_safety_hazards = check.Other_safety_hazards,
                                    Other_safety_hazards_state = check.Other_safety_hazards_state,
                                    semesterId = check.semesterId
                                };
                                for (int i = 0; i < check.laboratoryIds.Count; i++)
                                {
                                    newcheck.laboratoryId = check.laboratoryIds[i];

                                    try
                                    {
                                        //checkRecodHelp.Success = _checkService.addCheck(newcheck);
                                        if(_checkService.addCheck(newcheck))
                                        {
                                            Console.WriteLine("ok");
                                        }
                                        else
                                        {
                                            Console.WriteLine("notok");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //checkRecodHelp.Success = false;
                                        //checkRecodHelp.reason = ex.ToString();

                                        checkRecodHelps.Add(check.laboratoryIds[i]);
                                    }

                                }
                                processed = true;
                            }
                            if (processed)
                            {
                                //消息成功处理后，向消息队列返回确认状态
                                //channel.BasicAck(e.DeliveryTag, false);
                            }
                        }


                    }
                    catch
                    {
                        processed = false;
                    }

                    if (processed)
                    {
                        //发送确认回执
                        channel.BasicAck(ea.DeliveryTag, false);
                    }
                };

                string consumerTag = "login-consumer";
                //注册消费者
                channel.BasicConsume(queueName, false, consumerTag, false, false, null, consumer);
                #endregion


            }
            finally
            {
                //确保在退出前关闭连接和通道
                //channel.Close();
                //connection.Close();
            }


            return new JsonResult("");      
                           
            

        }


    }
}
